/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\StockCheck\QuatoDetail\EditStockCheck.tsx
 * @Date: 2021-11-26 09:31:34
 * @LastEditTime: 2023-02-20 15:08:28
 */
import React, { createRef } from 'react'
import { http, IUdFormItem, UdDrawer, UdForm, validators } from '@/lib'
import { Input, InputNumber } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import './approve.scss'
import InputNumberLinkOrder from './component/InputNumberLinkOrder'
import apis from '@/apis/AboutQuota'
import LinkOrders from './component/LinkOrders'

const { TextArea } = Input
interface IProps {
  detailDataSource: Record<string, any>
  record: any
  editTableData: (record: Record<string, any>) => void
  orderParams: Record<string, any>
}
interface IState {
  allowEditStock: string
  nowMove: null | number
}
export default class EditStockCheck extends React.Component<IProps, IState> {
  private record = { ...this.props.record }
  private labelCol: any = { span: 3 }
  private wrapperCol: any = { span: 17 }
  private form: WrappedFormUtils
  public cRef = createRef<any>()

  state: IState = {
    allowEditStock: '',
    nowMove: null,
  }

  componentDidMount() {
    this.setState({nowMove:this.record.nowMove})
    this.getDealerCheckStockStatus()
  }

  private getDealerCheckStockStatus = () => {
    let { detailDataSource: { brandCode, dealerCode } = {} } = this.props
    const userName = JSON.parse(sessionStorage.getItem('UaaSysInfo')).profile.username
    let params = {
      userName,
      brandCode,
      dealerCode,
    }
    http.get(apis.GetDealerCheckStockStatus, { params }).then(res => {
      let allowEditStock = res.data.allowEditStock
      this.setState({ allowEditStock })
    })
  }

  private onOk = e => {
    let { record, editTableData } = this.props
    this.form.validateFields((err, values) => {
      if (!err) {
        let params = { ...values, prodBarcode: record.prodBarcode }
        editTableData(params)
        e.close()
      } else {
        console.log(err)
      }
    })
  }

  private handLinkOrders = (): void => {
    let { orderParams } = this.props
    UdDrawer.open({
      title: '关联订单',
      width: '50%',
      content: <LinkOrders orderParams={orderParams} />,
      footer: null,
    })
  }

  //计算期间动销数
  private calcNowMove = () => {
    setTimeout(() => {
      let formValues = this.form.getFieldsValue()
      let beginningRealStock = formValues['beginningRealStock'] ?? null //期初库存
      let nowAog = formValues['nowAog'] ?? null //期间开单
      let allocateNumber = formValues['allocateNumber'] ?? null //调入调出
      let nowRealStock = formValues['nowRealStock'] ?? null //当前实物库存
      let onOrder = formValues['onOrder'] ?? null //当前未到货
      let nowMove = +beginningRealStock + +nowAog + +allocateNumber - +nowRealStock - +onOrder
      this.setState({ nowMove })
      this.form.setFieldsValue({ nowMove })
    }, 100)
  }

  render() {
    let { allowEditStock, nowMove } = this.state
    let items: IUdFormItem[] = [
      {
        label: '期初库存(含未到货)件',
        id: 'beginningRealStock',
        rules: [validators.required],
        render: () => (
          <InputNumber
            onBlur={this.calcNowMove}
            precision={1}
            style={{ width: '100%' }}
            readOnly={allowEditStock !== 'Y'}
          />
        ),
      },
      {
        label: '期间开单/件',
        id: 'nowAog',
        rules: [validators.required],
        render: () => (
          <InputNumberLinkOrder
            handLinkOrders={this.handLinkOrders}
            calcNowMove={this.calcNowMove}
            readOnly={allowEditStock !== 'Y'}
          />
        ),
      },
      {
        label: '调入调出',
        id: 'allocateNumber',
        rules: [validators.required],
        render: () => <InputNumber readOnly onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '当前实物库存/件',
        id: 'nowRealStock',
        rules: [validators.required],
        render: () => <InputNumber min={0} onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '当前未到货/件',
        id: 'onOrder',
        rules: [validators.required],
        render: () => <InputNumber min={0} style={{ width: '100%' }} precision={1} onBlur={this.calcNowMove} />,
      },
      {
        label: '期间动销数/件',
        id: 'nowMove',
        rules: [validators.required],
        render: () => (
          <InputNumber
            readOnly
            style={{ width: '100%' }}
            onChange={e => {
              console.log(e)
            }}
          />
        ),
      },
      {
        label: '下月订单计划/件',
        id: 'nextMonthOrderNum',
        render: () => <InputNumber precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '动销说明',
        id: 'nowMoveDes',
        rules: [nowMove !== null ? (nowMove < 0 ? validators.required : { required: false }) : { required: false }],
        render: <TextArea rows={3} placeholder="当动销数小于0需填写动销备注说明" />,
      },
      { label: '备注信息', id: 'remark', render: <TextArea rows={3} /> },
    ]
    return (
      <>
        <UdForm
          labelCol={this.labelCol}
          wrapperCol={this.wrapperCol}
          getForm={form => (this.form = form)}
          items={items}
          values={this.record}
        />
        <div style={{ fontSize: '12px', color: '#666' }}>
          <p>说明：</p>
          <p>1、期初库存（含未到货）：上期实物库存+上期未到货</p>
          <p>2、期间开单：上期盘点至本期盘点期间的下单数量</p>
          <p>3、当前实物：盘点时的库存数量</p>
          <p>4、当前未到货：盘点时所有下单未到货数</p>
          <p>5、期间动销数=期初库存+期间开单+调入调出-当前实物-当前未到货</p>
        </div>
      </>
    )
  }
}
